<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24" style="padding: 10px; border: 1px solid #e3e7ef">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入部门名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="姓名" prop="nickName">
            <el-input
              v-model="queryParams.nickName"
              placeholder="请输入用户名称"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item label="类型" prop="status">
            <el-select v-model="queryParams.status" placeholder="类型" clearable style="width: 240px">
              <el-option
                v-for="dict in dict.type.sys_docbase_user_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="入职时间">
            <el-date-picker
              v-model="JoinDate"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="生日">
            <el-date-picker
              v-model="dateRange"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <!-- <el-form-item label="岗位" prop="phonenumber">
            <el-select
              v-model="queryParams.postIds"
              placeholder="请选择岗位"
              clearable
              :style="{ width: '100%' }"
            >
              <el-option
                v-for="(item, index) in postOptions"
                :key="item.postId"
                :label="item.postName"
                :value="item.postId"
              ></el-option>
            </el-select>
          </el-form-item>-->
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8" v-if="isShowAdd">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['personnel:file:add']"
            >新增</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['personnel:file:edit']"
              >修改</el-button
            >
          </el-col>-->
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['personnel:file:remove']"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['personnel:file:export']"
            >导出</el-button>
          </el-col>
          <el-button
            size="mini"
            type="primary"
            @click="handleZzsq()"
            v-hasPermi="['personnel:contract:zzsq']"
          >转正申请</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleLzsq()"
            v-hasPermi="['personnel:quit:addQuit']"
          >离职申请</el-button>
          <!-- <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              :disabled="single"
              @click="handleDocCert"
              v-hasPermi="['personnel:file:add']"
              >维护档案资料</el-button
            >
          </el-col> -->
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              :disabled="single"
              @click="handleAddCertType"
              v-hasPermi="['personnel:file:add']"
              >维护项目资格证书</el-button
            >
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" border :data="userList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column type="index" label="序号" width="50" align="center" />
          <el-table-column show-overflow-tooltip label="状态" min-width="150">
            <template slot-scope="scope">
              <el-tag size="mini" :type="scope.row.draft==0||scope.row.draft==null?'info':''">{{ scope.row.draft==1?'已提交':'草稿' }}</el-tag>
            </template>
          </el-table-column>
          <!-- <el-table-column label="档案ID" align="center" prop="userDocBaseId" /> -->
          <el-table-column label="工号" align="center">
            <template slot-scope="scope">
              {{ scope.row.userName ? scope.row.userName : "--" }}
              <i
                v-if="scope.row.userName"
                v-hasPermi="['personnel:file:edit:code:index']"
                class="el-icon-edit"
                @click="handleEditCode(scope.row)"
              ></i>
            </template>
          </el-table-column>
          <el-table-column label="档案编号" width="150" align="center" prop="docNo" />
          <el-table-column label="真实姓名" align="center" prop="nickName" />
          <el-table-column label="登录账号" width="150" align="center">
            <template slot-scope="scope">{{ scope.row.phone ? scope.row.phone : "--" }}</template>
          </el-table-column>
          <el-table-column label="性别" align="center" prop="sex">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex" />
            </template>
          </el-table-column>

          <el-table-column label="出生日期" width="150" align="center" prop="birthDate" />
          <el-table-column
            label="部门"
            align="center"
            prop="join.deptName"
            :show-overflow-tooltip="true"
          />
          <el-table-column label="所在岗位" align="center" prop="join.roleName" show-overflow-tooltip />
          <el-table-column label="入职时间" width="150" align="center" prop="join.startDate" />
          <el-table-column width="100" label="是否有账号" align="center">
            <template slot-scope="scope">
              <el-link v-if="scope.row.hasAccount == 1" type="success" :underline="false">是</el-link>
              <el-link v-else-if="scope.row.hasAccount == 0" type="danger" :underline="false">否</el-link>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column width="100" label="是否确认信息" align="center">
            <template slot-scope="scope">
              <el-link v-if="scope.row.isSure == 1" type="success" :underline="false">是</el-link>
              <el-link v-else-if="scope.row.isSure == 0" type="danger" :underline="false">否</el-link>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column label="人员分类" align="center">
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.sys_docbase_user_type"
                :value="scope.row.join.userTypeValue"
              />
            </template>
          </el-table-column>

          <el-table-column
            label="操作"
            align="center"
            width="160"
            fixed="right"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                v-if="scope.row.draft==1"
                v-hasPermi="['personnel:file:info']"
                @click="handleDetail(scope.row)"
              >详情</el-button>

              <el-button
                v-if="scope.row.isSure == 0"
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['personnel:file:edit']"
              >修改</el-button>
              <el-button
                v-if="(scope.row.isSure != 1 && scope.row.hasAccount == 0) && (scope.row.isSure == 0 && scope.row.hasAccount == 0)"
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['personnel:file:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-tabs v-model="form.type" @tab-click="changeTab">
          <el-tab-pane label="公路/水运" name="1"></el-tab-pane>
          <el-tab-pane label="建设试验" name="2"></el-tab-pane>
          <el-tab-pane label="建设审核" name="3"></el-tab-pane>
        </el-tabs>
        <el-row>
          <el-col :span="24">
            <el-form-item label="资格证书" prop="certTypeId">
              <treeselect
                multiple
                v-model="form.certTypeId"
                :options="cretList"
                :normalizer="normalizer"
                placeholder="选择资格证书"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="editCodeShow" title="修改工号" width="500px" append-to-body>
      <el-form ref="formEdit" :model="formEdit" :rules="rules" label-width="120px">
        <el-form-item label="新工号" prop="userName">
          <el-input
            v-model="formEdit.userName"
            placeholder="请输入新工号"
            clearable
            :style="{ width: '100%' }"
          ></el-input>
        </el-form-item>
      </el-form>
      <template slot="footer">
        <el-button size="mini" @click="editCodeShow = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="saveCode">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { checkRow } from "@/utils/ruoyi.js";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { optionselectPost } from "@/api/system/post.js";
import { listCertType } from "@/api/system/qualification.js";
import { deptTreeSelect, updateCode } from "@/api/system/user";
import {
  delDocBase,
  listDocBase,
  batchAddUserDocCertType,
  userDocCertType
} from "@/api/finance/personnel/file.js";
export default {
  name: "File",
  dicts: [
    "sys_user_sex",
    "sys_docbase_political",
    "sys_docbase_marital",
    "sys_docbase_professional",
    "sys_docbase_zzdj",
    "sys_docbase_user_type"
  ],
  components: { Treeselect },

  data() {
    return {
      editCodeShow: false,
      formEdit: {},
      isShowAdd: true,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "维护项目资格证书",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      JoinDate: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: { type: "1", certTypeId: undefined },
      rules: {
        certTypeId: [
          { required: true, message: "资格证书不能为空", trigger: "blur" }
        ],
        userName: [{ required: true, message: "工号不能为空", trigger: "blur" }]
      },
      defaultProps: {
        children: "children",
        label: "label"
      },

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nickName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined,
        person: 0
      },
      openCertType: false,
      cretList: []
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    const str = sessionStorage.getItem('queryParams');
    if (str) {
      this.queryParams = JSON.parse(str);
      this.queryParams.person = 0
      if (this.queryParams.startJoinDate) {
        this.JoinDate.push(this.queryParams.startJoinDate, this.queryParams.endJoinDate)
      }
      if (this.queryParams.startBirthDate) {
        this.dateRange.push(this.queryParams.startBirthDate, this.queryParams.endBirthDate)
      }
      setTimeout(() => {
        sessionStorage.removeItem('queryParams');
      }, 500)
    }
    this.getList();
    this.optionselectPost();
    this.getDeptTree();
  },
  methods: {
    /** 转换资格证书数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.certTypeId,
        label: node.certTypeName,
        children: node.children
      };
    },
    getCretList() {
      listCertType({ type: this.form.type }).then(response => {
        this.cretList = this.handleTree(response.data, "certTypeId");
      });
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      this.queryParams = this.addDateRangeTime(
        this.queryParams,
        this.dateRange,
        "startBirthDate",
        "endBirthDate"
      );
      listDocBase(
        this.addDateRangeTime(
          this.queryParams,
          this.JoinDate,
          "startJoinDate",
          "endJoinDate"
        )
      ).then(response => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.handleQuery();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        certTypeId: undefined,
        certTypeName: undefined,
        type: "1"
      };

      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleZzsq() {
      sessionStorage.setItem('queryParams', JSON.stringify(this.queryParams));
      this.$router.push("/finance/personnel/zzsq");
    },
    handleLzsq() {
      sessionStorage.setItem('queryParams', JSON.stringify(this.queryParams));
      this.$router.push("/finance/personnel/addQuit");
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.JoinDate = [];
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.deptId = undefined;
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userDocBaseId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    /** 新增按钮操作 */
    handleAdd() {
      sessionStorage.setItem('queryParams', JSON.stringify(this.queryParams));
      this.$router.push("./fileAdd");
    },
    optionselectPost() {
      optionselectPost().then(response => {
        this.postOptions = response.data;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      sessionStorage.setItem('queryParams', JSON.stringify(this.queryParams));
      const configId = row.userDocBaseId || this.ids;
      let e;
      if (Array.isArray(configId)) {
        e = this.userList.find(i => configId.includes(i.userDocBaseId));
      } else {
        e = this.userList.find(i => configId == i.userDocBaseId);
      }
      // if (e.isSure == 1) {
      //   this.$message.warning("信息确认不允许修改");
      //   return;
      // }
      this.$router.push("./fileAdd?isEdit=true&id=" + configId);
    },
    handleDetail(row) {
      sessionStorage.setItem('queryParams', JSON.stringify(this.queryParams));
      this.$router.push("./fileAdd?isInfo=true&id=" + row.userDocBaseId);
    },
    handleDocCert(row) {
      sessionStorage.setItem('queryParams', JSON.stringify(this.queryParams));
      const configId = row.userDocBaseId || this.ids;
      this.$router.push("./docCert?id=" + configId);
    },
    handleAddCertType(row) {
      sessionStorage.setItem('queryParams', JSON.stringify(this.queryParams));
      const configId = row.userDocBaseId || this.ids;
      this.$router.push("./certType?id=" + configId);

      return;
      this.reset();
      this.getCretList();
      this.form.userDocBaseId = configId.toString();
      userDocCertType({
        userDocBaseId: this.form.userDocBaseId,
        type: this.form.type
      }).then(res => {
        this.form.certTypeId = res.data
          .filter(e => e.selectFlag)
          .map(i => i.certTypeId);
        console.log(res.data);
      });
      this.open = true;
    },
    changeTab() {
      this.form.certTypeId = [];
      this.getCretList();
      userDocCertType({
        userDocBaseId: this.form.userDocBaseId,
        type: this.form.type
      }).then(res => {
        this.form.certTypeId = res.data
          .filter(e => e.selectFlag)
          .map(i => i.certTypeId);
        console.log(res.data);
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          batchAddUserDocCertType(this.form).then(response => {
            this.$modal.msgSuccess("设置成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    handleEditCode(e) {
      this.formEdit.userId = e.userId;
      this.editCodeShow = true;
    },
    saveCode() {
      this.$refs["formEdit"].validate(valid => {
        if (valid) {
          updateCode(this.formEdit).then(response => {
            this.$modal.msgSuccess("操作成功");
            this.editCodeShow = false;
            this.getList();
          });
        }
      });
    },
    handleExport() {
      this.download(
        "system/docBase/export",
        {
          ...this.queryParams,
          userDocBaseIds: this.ids.toString()
        },
        `人事档案记录表_${this.parseTime(
          new Date().getTime(),
          "{y}-{m}-{d}"
        )}.xlsx`
      );
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userDocBaseId || this.ids;
      console.log(userIds);
      let name = checkRow(
        userIds,
        this.userList,
        "userDocBaseId",
        "DELETE",
        "nickName"
      );
      let flag;
      if (Array.isArray(userIds)) {
        flag = this.userList
          .filter(i => userIds.includes(i.userDocBaseId))
          .some(e => !(e.isSure != 1 && e.hasAccount == 0));
      } else {
        flag = this.userList
          .filter(i => userIds == i.userDocBaseId)
          .some(e => !(e.isSure != 1 && e.hasAccount == 0));
      }
      if (flag) {
        this.$message.warning("信息确认不允许删除");
        return;
      }
      console.log(flag);
      this.$modal
        .confirm('是否确认删除姓名为"' + name + '"的数据项？')
        .then(function() {
          return delDocBase(userIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    }
  }
};
</script>
